package com.itmk.config.web.material_category.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.config.web.material_category.entity.MaterialCategory;
import com.itmk.config.web.material_category.entity.PageParm;
import com.itmk.config.web.material_category.service.MaterialCategoryService;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/category")
public class MaterialCategoryController {

    @Autowired
    private MaterialCategoryService materialCategoryService;

    @PostMapping
    public ResultVO add(@RequestBody MaterialCategory category){
       if ( materialCategoryService.save(category)){
           return ResultUtils.success("新增成功");
       }
        return ResultUtils.error("新增失败");

    }

    @PutMapping
    public ResultVO edit(@RequestBody MaterialCategory category){
        if ( materialCategoryService.updateById(category)){
            return ResultUtils.success("编辑成功");
        }
        return ResultUtils.error("编辑失败");

    }

    @DeleteMapping("/{categoryId}")
    public ResultVO delete(@PathVariable("categoryId") Long categoryId){
        if ( materialCategoryService.removeById(categoryId)){
            return ResultUtils.success("删除成功");
        }
        return ResultUtils.error("删除失败");

    }

    @GetMapping("/list")
    public ResultVO list(PageParm parm){
        IPage<MaterialCategory> page = new Page<>(parm.getCurrentPage(),parm.getPageSize());
        QueryWrapper<MaterialCategory> query = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(parm.getCategoryName())){
            query.lambda().like(MaterialCategory::getCategoryName,parm.getCategoryName());
        }
        query.lambda().orderByDesc(MaterialCategory::getOrderNum);
        IPage<MaterialCategory> list = materialCategoryService.page(page,query);
        return ResultUtils.success("查询成功",list);

    }
}
